package com.saohuobang.test.util;

import com.alibaba.fastjson.JSON;
import com.saohuobang.test.model.core.APIResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者 yaohua.liu
 * 日期 2015-11-13 16:00
 * 包名 com.saohuobang.test.util
 * 说明 ...
 */
public class FilterUtils {

    /**
     * 判断该reauest是否在忽略验证的URI列表中
     *
     * @param request           HttpServletRequest
     * @param blackServletPaths 黑名单 URI列表
     * @return
     */
    public static boolean isInForbidAccessPaths(HttpServletRequest request, List<String> blackServletPaths) {
        String servletPath = request.getServletPath();
        // 处理 黑名单 URI列表
        for (String sz : blackServletPaths) {
            if (matchIgnoreServletPath(sz, servletPath)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断该reauest是否在忽略验证的URI列表中
     *
     * @param request         HttpServletRequest
     * @param ignoreCheckList 略验证的URI列表
     * @return
     */
    public static boolean isIgnoreCheckValid(HttpServletRequest request, List<String> ignoreCheckList) {
        String servletPath = request.getServletPath();
        // 处理忽略列表
        for (String sz : ignoreCheckList) {
            if (matchIgnoreServletPath(sz, servletPath)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取真实返回的url+参数
     *
     * @param url url
     * @param req HttpServletRequest
     * @return
     */
    public static String getStateURL(String url, HttpServletRequest req) {

        Enumeration enu = req.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            if (url.indexOf("?") == -1) { //没有url传参
                url += "?" + paraName + "=" + req.getParameter(paraName);
            } else {
                url += "&" + paraName + "=" + req.getParameter(paraName);
            }
        }
        return url;
    }

    /**
     * Return <code>true</code> if the context-relative request path matches the requirements of the specified filter
     * mapping; otherwise, return <code>false</code>.
     *
     * @param testPath    URL mapping being checked
     * @param requestPath Context-relative request path of this request
     */
    public static boolean matchIgnoreServletPath(String testPath, String requestPath) {

        if (testPath == null)
            return (false);

        // Case 1 - Exact Match
        if (testPath.equals(requestPath))
            return (true);

        // Case 2 - Path Match ("/.../*")
        if (testPath.equals("/*"))
            return (true);
        if (testPath.endsWith("/*")) {
            if (testPath.regionMatches(0, requestPath, 0, testPath.length() - 2)) {
                if (requestPath.length() == (testPath.length() - 2)) {
                    return (true);
                } else if ('/' == requestPath.charAt(testPath.length() - 2)) {
                    return (true);
                }
            }
            return (false);
        }

        // Case 3 - Extension Match
        if (testPath.startsWith("*.")) {
            int slash = requestPath.lastIndexOf('/');
            int period = requestPath.lastIndexOf('.');
            if ((slash >= 0) && (period > slash) && (period != requestPath.length() - 1)
                    && ((requestPath.length() - period) == (testPath.length() - 1))) {
                return (testPath.regionMatches(2, requestPath, period + 1, testPath.length() - 2));
            }
        }

        // Case 4 - "Default" Match
        return (false); // NOTE - Not relevant for selecting filters
    }

    /**
     * 获取真实返回的url+参数
     *
     * @param req
     * @return
     */
    public static String getUrlInfo(HttpServletRequest req) {

        String url = "";
        if (req.getServerPort() == 80) {
            url = req.getScheme() + "://" + req.getServerName() + req.getContextPath() + req.getServletPath();
        } else {
            url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + req.getServletPath();
        }
        Enumeration enu = req.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            if (url.indexOf("?") == -1) { // 没有url传参
                url += "?" + paraName + "=" + req.getParameter(paraName);
            } else {
                url += "&" + paraName + "=" + req.getParameter(paraName);
            }
        }
        return url;
    }


    public static void resContent(HttpServletResponse res, int retStatus, String retMsg) throws IOException {
        String resContentJson = JSON.toJSONString(APIResponse.returnFail(retStatus,retMsg));
        res.setContentType("text/html;charset=UTF-8");
        res.setHeader("Pragma", "No-cache");
        res.setHeader("Cache-Control", "no-cache");
        res.setDateHeader("Expires", 0);
        res.getWriter().write(resContentJson);
        res.getWriter().flush();
    }
}
